package com.wngbms.netty.gatewaydemo.handler;

import com.wngbms.netty.gatewaydemo.filter.HttpRequestFilter;
import com.wngbms.netty.gatewaydemo.handler.bizhandler.BaseDoHttpInboundHandler;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.util.ReferenceCountUtil;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@ChannelHandler.Sharable
public class HttpInboundHandler extends ChannelInboundHandlerAdapter {

    private BaseDoHttpInboundHandler handler;
    private HttpRequestFilter httpRequestFilter;

    public HttpInboundHandler(BaseDoHttpInboundHandler baseDoHttpInboundHandler,
                              HttpRequestFilter httpRequestFilter) {
        this.handler = baseDoHttpInboundHandler;
        this.httpRequestFilter = httpRequestFilter;
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        try {
            FullHttpRequest fullHttpRequest = (FullHttpRequest) msg;
            handler.handle(fullHttpRequest, ctx, httpRequestFilter);
        } catch (Exception e) {
            log.error("exp", e);
        } finally {
            ReferenceCountUtil.release(msg);
        }
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }
}
